package com.hxd.mall.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.hxd.mall.R
import com.hxd.mall.base.IBaseWidgetView
import com.hxd.mall.constant.HxdGlobalInfo
import com.hxd.mall.utils.open.FaskClickUitl
import com.hxd.mall.utils.open.NetUtil
import com.hxd.mall.utils.open.ToastUtil
import com.hxd.mall.utils.open.addSetOnClickListener
import com.hxd.mall.widget.verifycode.VerifyCodeView

/**
 * 验证码组件(input: 0 注册验证码，1忘记密码验证码)
 * 验证码支持4位或6位
 * Created by qishuai on 2018/7/23.
 */
@SuppressLint("SetTextI18n")
class HxdVerifyCodeView(context: Context?, var attrs: AttributeSet?) : LinearLayout(context, attrs),
    IBaseWidgetView {
    // 文本框类型
    private var mInputType = 0
    // 验证码位数4或6
    private var mInputCodeLength = 0
    // title name tv
    private lateinit var mTvTitleNameTip: TextView
    // title name desc 短信已经方式到123
    private lateinit var mTvTitleNameDescTip: TextView
    // 倒计时或重新发送
    private lateinit var mTvSendSmsTip: TextView
    // input error tip tv
    private lateinit var mTvErrorTip: TextView
    // 服务协议
    private lateinit var mViewDealRoot: View
    // 协议复选框
    private lateinit var mIvDealSelector: ImageView
    // 协议地址
    private lateinit var mTvDealUrl: TextView
    // 验证码框
    private lateinit var mVerifyCodeView: VerifyCodeView
    private lateinit var mBtnNext: Button
    // 用户协议checkbox
    private var mDealDefaultState = false
    // 验证码是否输入完成
    private var mVerifyCodeDone = false

    init {
        setupData()
        setupView()
        setupLayout()
        setupGesture()
    }

    override fun setupView() {
        LayoutInflater.from(context).inflate(R.layout.widget_phone_verify_code, this)
        // get view
        mTvTitleNameTip = this.findViewById(R.id.tv_title_name_tip)
        mTvTitleNameDescTip = this.findViewById(R.id.tv_title_name_desc_tip)
        mTvSendSmsTip = this.findViewById(R.id.tv_verify_code_send)
        mTvErrorTip = this.findViewById(R.id.tv_error_tip)
        mVerifyCodeView = this.findViewById(R.id.verify_code)
        mBtnNext = this.findViewById(R.id.btn_next)
        mViewDealRoot = this.findViewById(R.id.layout_deal_see_root)
        mIvDealSelector = this.findViewById(R.id.iv_deal_selector)
        mTvDealUrl = this.findViewById(R.id.tv_deal_url)
    }

    override fun setupData() {
        // 获取文本框类型
        val typeArray = context?.obtainStyledAttributes(attrs, R.styleable.HxdVerifyCodeView)
        mInputType = typeArray?.getInt(R.styleable.HxdVerifyCodeView_et_code_type, -1) ?: 0
        mInputCodeLength = typeArray?.getInt(R.styleable.HxdVerifyCodeView_et_code_length, -1) ?: 0
        typeArray?.recycle()
    }

    override fun setupLayout() {
        // init view show
        when (mInputType) {
            0 -> initViewRegisterType()
            1 -> initViewForgetPwdType()
            3 -> initViewUpdatePhoneNumberType()
        }
    }

    override fun setupGesture() {

    }

    //---------------------------------private method-------------------------------------------------
    /**
     * 修改手机号-验证码
     */
    private fun initViewUpdatePhoneNumberType() {
        mViewDealRoot.visibility = View.GONE
        mTvTitleNameTip.text = context.getString(R.string.security_modify_phone)
        initVerifyCodeCommon()
    }

    /**
     * 忘记密码-验证码
     */
    private fun initViewForgetPwdType() {
        //mBtnNext.tag = "-103"
        mViewDealRoot.visibility = View.GONE
        initVerifyCodeCommon()
    }

    /**
     * 注册-验证码
     */
    private fun initViewRegisterType() {
        //mBtnNext.tag = "-103"
        mViewDealRoot.visibility = View.VISIBLE
        initVerifyCodeCommon()
    }

    private fun initVerifyCodeCommon() {
        mTvErrorTip.text = ""
        mBtnNext.run {
            isEnabled = false
            setBackgroundResource(R.mipmap.btn_disabled)
        }

        mVerifyCodeView.setCodeLength(mInputCodeLength)
        mVerifyCodeView.setInputCompleteListener(object : VerifyCodeView.InputCompleteListener {
            override fun inputComplete() {
                mVerifyCodeDone = true
                handlerCodeDone()
            }

            override fun invalidContent() {
                mVerifyCodeDone = false
                handlerCodeDone()
            }
        })

        // 协议 复选框
        if (mDealDefaultState) {
            mIvDealSelector.setImageResource(R.mipmap.deal_checkbox_selected)
        } else {
            mIvDealSelector.setImageResource(R.mipmap.deal_checkbox_normal)
        }

        mIvDealSelector.setOnClickListener {
            if (mDealDefaultState) {
                mDealDefaultState = false
                mIvDealSelector.setImageResource(R.mipmap.deal_checkbox_normal)
            } else {
                mDealDefaultState = true
                mIvDealSelector.setImageResource(R.mipmap.deal_checkbox_selected)
            }

            // net verify
            handlerCodeDone()
        }
    }

    /**
     * 验证码输入完成 && 勾选协议
     * 开始网络请求
     */
    private fun handlerCodeDone() {
        // 忘记密码 不需要验证协议勾选
        if (checkEtVerifyCodeDone() && mInputType == 1) {
            mBtnNext.isEnabled = true
            mBtnNext.setBackgroundResource(R.mipmap.btn_normal)
        } else if (checkEtVerifyCodeDone() && mInputType == 0 && mDealDefaultState) {
            // 注册，需要协议勾选
            mBtnNext.isEnabled = true
            mBtnNext.setBackgroundResource(R.mipmap.btn_normal)
        } else if (checkEtVerifyCodeDone() && mInputType == 3) {
            mBtnNext.isEnabled = true
            mBtnNext.setBackgroundResource(R.mipmap.btn_normal)
        } else {
            mBtnNext.isEnabled = false
            mBtnNext.setBackgroundResource(R.mipmap.btn_disabled)
        }
    }

    private fun checkEtVerifyCodeDone(): Boolean {
        return mVerifyCodeDone
    }

    fun setDealUrlListener(callback: () -> Unit) {
        mTvDealUrl.setOnClickListener(OnClickListener {
            if (!NetUtil.isNetworkAvailable(HxdGlobalInfo.instance)) {
                ToastUtil.showToast(HxdGlobalInfo.instance.getString(R.string.net_error_tip))
                return@OnClickListener
            }
            if (FaskClickUitl.isFastClick()) {
                return@OnClickListener
            }
            callback()
        })
    }

    /**
     * 提示短信已经发送到手机号
     */
    fun setSendSmsTip(phoneNumber: String) {
        if (phoneNumber.isNotEmpty())
            mTvTitleNameDescTip.text = context.getString(R.string.login_input_phone_verify_code_tip_desc) + phoneNumber.substring(0, 3) + " **** " + phoneNumber.substring(7)
    }

    /**
     * 提示倒计时（输入全部字段）
     * (59秒后可重新发送)
     */
    fun setSendCountDownTip(message: String) {
        mTvSendSmsTip.visibility = View.VISIBLE
        mTvSendSmsTip.text = message
        mTvSendSmsTip.setTextColor(ContextCompat.getColor(context, R.color.color_CCCCCC))
        mTvSendSmsTip.isClickable = false
    }

    /**
     * 重新发送（输入全部字段）
     * (重新发送验证码)
     */
    fun setSendCountDownOverTip() {
        mTvSendSmsTip.visibility = View.VISIBLE
        mTvSendSmsTip.text = context?.getString(R.string.login_send_verify_code_desc_again)
        mTvSendSmsTip.setTextColor(ContextCompat.getColor(context, R.color.color_1153FC))
        mTvSendSmsTip.isClickable = true
    }

    /**
     * 清空提示
     */
    fun clearSendCountTip() {
        mTvSendSmsTip.text = ""
    }

    /**
     * 设置重新发送事件
     */
    fun setSendCountDownOverListener(callback: () -> Unit) {
        mTvSendSmsTip.setOnClickListener(OnClickListener {
            if (FaskClickUitl.isFastClick()) {
                return@OnClickListener
            }
            callback()
        })
    }

    //---------------------------------public method-------------------------------------------------
    /**
     * 错误提示,外部调用
     */
    fun setErrorTip(message: String) {
        mTvErrorTip.text = message
    }

    fun clearInputText() {
        mVerifyCodeView.clearInput()
    }

    fun getVerifyCode(): String {
        return mVerifyCodeView.editContent
    }

    /**
     * 输入错误背景色变红
     */
    fun setEtErrorTip(backgroundId: Int) {
        mVerifyCodeView.setEtErrorTip(backgroundId)
    }

    fun setVerifyCodeInputDoneListener(callback: () -> Unit) {
        addSetOnClickListener(mBtnNext) {
            // 验证码输入完成埋点
//            if (mInputType == 0) {
//                LoganUtil.clickEndTime("102")
//            } else if (mInputType == 1) {
//                LoganUtil.clickEndTime("107")
//            }
            callback()
        }
    }

    fun getButtonNext(): Button {
        return mBtnNext
    }
}